package com.aorise.service.system.impl;

import com.aorise.mapper.system.UserMapper;
import com.aorise.mapper.system.UserRoleMapper;
import com.aorise.model.response.UserInfoRes;
import com.aorise.model.system.*;
import com.aorise.model.request.RegisterUserReq;
import com.aorise.model.response.UserListRes;
import com.aorise.service.system.AuthorityService;
import com.aorise.service.system.RoleService;
import com.aorise.service.system.UserService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.MD5Utils;
import com.aorise.utils.Page;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zhouhao
 * @Date: 2019/4/26
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleService roleService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public List<User> selectByRole(Integer roid) {
//        UserExample userExample = new UserExample();
//        userExample.or().andRole_idEqualTo(roid);
//        List<User> users = userMapper.selectByExample(userExample);
//        return users;
        return null;
    }

    @Override
    public List<User> selectByAccount(String account,Integer userType) {
        UserExample userExample = new UserExample();
        userExample.or().andAccountEqualTo(account);
        userExample.or().andUserTypeEqualTo(userType);
        userExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        List<User> users = userMapper.selectByExample(userExample);
        if(CollectionUtils.isNotEmpty(users)){
            /**查询用户角色*/
            User user = users.get(0);
            List<Role> roles = roleService.selectByUserId(user);
            user.setRoles(roles);
            /**查询用户权限*/
            if(CollectionUtils.isNotEmpty(roles)) {
                roles.stream().forEach(role -> {
                    role.setAuthorities(authorityService.selectByRoleId(role.getId()));
                });
            }
        }
        return users;
    }

    @Override
    public Page selectUserList(UserListRes userRes){
        Page page = new Page();
        Integer pageNum = userRes.getPageNum();
        Integer pageSize = userRes.getPageSize();
        pageSize = pageSize==null?10:pageSize;
        pageNum = pageNum==null?1:pageNum;
        page.setCurrentPage(pageNum.longValue());
        page.setEveryPage(pageSize.longValue());
        long count =userMapper.selectUserCount(userRes);
        if(count >0) {
            page.setTotalCount(count);
            page.setTotalPage(count, page.getEveryPage());
            if (page.getCurrentPage() > 0 && page.getEveryPage() > 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("userRes", userRes);
                map.put("beginIndex", page.getBeginIndex());
                map.put("endinIndex", page.getEndinIndex());
                map.put("state",ConstDefine.STATE_ABLE);
                /**查询分页条数*/
                page.setList(userMapper.selectUserList(map));
            }
        }else {
            page.setTotalCount(0L);
        }
        return page;
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = { Exception.class })
    @Override
    public boolean addUser(RegisterUserReq userReq){
        Integer loginUserId = getLoginUser().getId();
        Integer userType = (userReq.getUserType() == null) ? ConstDefine.USER_TYPE_SYS : userReq.getUserType();
        User user = User.builder().account(userReq.getAccount()).username(userReq.getUsername())
                    .userType(userType).password(MD5Utils.getEncryptedPwd(ConstDefine.USER_PWD))
                    .phone(userReq.getPhone()).deptId(userReq.getDeptId()).orgId(userReq.getOrgId())
                    .createUser(loginUserId).updateUser(loginUserId).build();
        userMapper.insert(user);
        return getBoolean(userRoleMapper.insert(UserRole.builder().userId(user.getId()).roleId(userReq.getRoleId())
                .createUser(loginUserId).updateUser(loginUserId).build()));
    }

    @Override
    public boolean deleteUser(Integer id) {
        User user = getLoginUser();
        return getBoolean(userMapper.updateByPrimaryKeySelective(User.builder().id(id)
                .state(ConstDefine.STATE_DISABLE).updateTime(new Date()).updateUser(user.getId()).build()));
    }

    @Override
    public boolean resetPwdByUserId(@NotNull(message = "用户ID不能为空") Integer userId){
        User user = getLoginUser();
        return getBoolean(userMapper.updateByPrimaryKeySelective(User.builder().id(userId)
                .password(MD5Utils.getEncryptedPwd(ConstDefine.USER_PWD)).updateTime(new Date()).
                        updateUser(user.getId()).build()));
    }

    @Override
    public boolean changePwdById(Integer userId,String password){
        User user = getLoginUser();
        return getBoolean(userMapper.updateByPrimaryKeySelective(User.builder().id(userId)
                .password(MD5Utils.getEncryptedPwd(password)).updateTime(new Date()).
                        updateUser(user.getId()).build()));
    }

    @Override
    public User selectByUserId(Integer userId) {
        UserExample userExample = new UserExample();
        userExample.or().andIdEqualTo(userId);
        userExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        return userMapper.selectByExample(userExample).get(0);
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = { Exception.class })
    @Override
    public boolean updateUser(RegisterUserReq userReq,Integer userId) {
        User loginUser = getLoginUser();
        User user =new User();
        BeanUtils.copyProperties(userReq,user,getNullPropertyNames(userReq));
        user.setUpdateTime(new Date());
        user.setUpdateUser(loginUser.getId());
        user.setId(userId);
        user.setAccount(null);
        user.setUserType(null);
        if(!getBoolean(userMapper.updateByPrimaryKeySelective(user))){
            return false;
        }
        UserRoleExample userRoleExample = new UserRoleExample();
        userRoleExample.or().andUser_idEqualTo(userId);
        userRoleMapper.deleteByExample(userRoleExample);
        return getBoolean(userRoleMapper.insert(UserRole.builder().userId(userId).roleId(userReq.getRoleId()).build()));
    }

    @Override
    public UserInfoRes selectUserInfoByUserId(Integer userId) {
        Map map = Maps.newHashMap();
        userId = userId==null?getLoginUser().getId():userId;
        map.put("userId",userId);
        map.put("state",ConstDefine.STATE_ABLE);
        return userMapper.selectUserInfoByUserId(map);
    }

    @Override
    public List<User> selectUserByApp() {
        Map map = Maps.newHashMap();
        map.put("permission","APPDLSY");
        map.put("state",ConstDefine.STATE_ABLE);
        return userMapper.selectUserByApp(map);
    }

    @Override
    public String isWorkUser(Integer userId) {
        int workOrder =0;
        int migration =1;
        int halt =2;
        Map map = Maps.newHashMap();
        map.put("userId",userId);
        map.put("wStatus",ConstDefine.WORK_ORDER_STATUS_FNISHI);
        map.put("mStatus",ConstDefine.APPROVE_STATUS_PASS);
        map.put("state",ConstDefine.STATE_ABLE);
        List<Integer> list = userMapper.isWorkUser(map);
        if(CollectionUtils.isNotEmpty(list)){
            for(int i =0;i<list.size();i++){
                if(getBoolean(list.get(i))){
                    if(workOrder == i){
                        return "该用户尚有未处理的运维工单,无法删除";
                    }
                    if(migration == i){
                        return "该用户尚有未处理的迁建记录,无法删除";
                    }
                    if(halt == i){
                        return "该用户尚有未处理的停机记录,无法删除";
                    }
                }
            }
        }
        return null;
    }


}
